<%@page import="common.FileManipulation"%>
<%@page import="models.EmailDTO"%>
<%@page import="services.EmailServiceImpl"%>
<%@page import="java.io.File"%>
<%@page import="java.util.*"%>
<%@page import="com.ckeditor.CKEditorConfig;"%>

<%@ page language="java" contentType="text/html; charset=ISO-8859-1" pageEncoding="ISO-8859-1"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<%@ taglib uri="http://ckeditor.com" prefix="ckeditor" %>
<html>
<head>
	<meta http-equiv="content-type" content="text/html; charset=ISO-8859-1">
	<title>Email Users</title>
    <link href="../Css/popup.css" rel="stylesheet" type="text/css" >
	<link href="../Css/skin/ui.dynatree.css" rel="stylesheet" type="text/css" id="skinSheet">
		
	<script src="../Js/jquery.js" type="text/javascript"></script>
	<script src="../Js/jquery-ui.custom.js" type="text/javascript"></script>
	<!-- <script src="../Js/jquery-ui-1.8.16.custom.min.js" type="text/javascript"></script>  -->
	<script src="../Js/jquery.cookie.js" type="text/javascript"></script>	

	<script src="../Js/jquery.dynatree.js" type="text/javascript"></script>


	<script type="text/javascript">
	  
		$(function(){
			
			/**************************** Any Close button ******************************************/
	
			//Displays a confirmation window on Close button inside the pop up window.
			$(".Close").click(function (e) {
			
			    var confirmed = confirm("Are you sure you want to close?");
			    if (confirmed) {
			        HideDialog();
					$('#MyForm').submit();
			        //e.preventDefault();
			    }
			});
			
				
			/***************************** Dynatree ************************************************/
			$("#tree").dynatree({
			  //Tree parameters
			  persist: true,
			  checkbox: true,
			  selectMode: 3,
			  activeVisible: true,
			 
			  //Un/check real checkboxes recursively after selection
			  onSelect: function(select, dtnode) {
			    dtnode.visit(function(dtnode){
			      $("#chb-"+dtnode.data.key).attr("checked",select);
			      },null,true);
			     ("#MyForm").submit();
			  },       
			  //Hack to prevent appearing of checkbox when node is expanded/collapsed
			  onExpand: function(select, dtnode) {
			    $("#chb-"+dtnode.data.key).attr("checked",dtnode.isSelected()).addClass("hidden");
			  }
			});
	      
			//Hide real checkboxes
			$("#tree :checkbox").addClass("hidden");
			//Update real checkboxes according to selections
			$.map($("#tree").dynatree("getTree").getSelectedNodes(),
			  function(dtnode){
			    $("#chb-"+dtnode.data.key).attr("checked",true);
			    dtnode.activate();
			  });
	      
	      
			$("#btnToggleSelect").click(function(){
				$("#tree").dynatree("getRoot").visit(function(node){
					node.toggleSelect();
				});
				return false;
			});
			$("#btnDeselectAll").click(function(){
				$("#tree").dynatree("getRoot").visit(function(node){
					node.select(false);
				});
				return false;
			});
			$("#btnSelectAll").click(function(){
				$("#tree").dynatree("getRoot").visit(function(node){
					node.select(true);
				});
				return false;
			});
			
			/***************************** Modal Window *********************************************/
			
			function ShowDialog(modal) {
			    $("#overlay").show();
			    $("#dialog").fadeIn(300);
			
			    if (modal) {
			        $("#overlay").unbind("click");
			    }
			    else {
			        $("#overlay").click(function (e) {
			            HideDialog();
			        });
			    }
			}
			
			function HideDialog() {
			    $("#overlay").hide();
			    $("#dialog").fadeOut(300);
			} 
			
			//Show dialog
			$("#btnAddEmail").click(function(e) {
			    ShowDialog(true);
			    e.preventDefault();
			});
			
			//Send new email account  
			$("#aAddEmail").click(function(e) {
				
				var emailAddressVal = $("#txtEmail").val();
				var emailReg = /^([\w-\.]+@([\w-]+\.)+[\w-]{2,4})?$/;
				 
				if(emailAddressVal == '')
				{
					$("#txtError").html("Please enter your email address.");
					e.preventDefault();
					
				}else if (!emailReg.test(emailAddressVal))
				{
					$("#txtError").html("Enter a valid email address."); 
					e.preventDefault();
					
				}else
				{
					//Empty form action
					$('#MyForm')[0].setAttribute('action', 'ManageEmail');
					
					$.post(	"ManageEmail", 
		            	   	{emailAddress:emailAddressVal, actionType: "AddEmail"}, 
		            	   	function(data) {
		                		$("#txtError").html("Email has been added.");
		            	   	}
		           	);
				
				}
			
			});
			
			//Delete selected email addresses
			$("#btnDeleteEmail").click(function(e) {
				
				$('#MyForm').get(0).setAttribute('action', 'ManageEmail');
				
				var params = [ { name: "actionType", value: "DeleteEmail"}];
				
			    $.each(params, function(i,param){
			        $('<input />').attr('type', 'hidden')
			            .attr('name', param.name)
			            .attr('value', param.value)
			            .appendTo('#MyForm');
			        
			    var confirmed = confirm("Are you sure you want to delete the email address(es)?");
			    if (confirmed) {
			    	
			        e.preventDefault();
					$('#MyForm').submit();

			    }else
			    { 
			    	e.preventDefault();
			    }				
				
				});
			    
			});
					
			//Send Newsletter
			$("#btnSendNewsletter").click(function (e) {
				
				$('#MyForm').get(0).setAttribute('action', 'Newsletter');
				e.preventDefault();
				$('#MyForm').submit();
				
			});		
			
			//form submit event
			/*$('#MyForm').submit(function(){ //listen for submit event
				
				var params = [{ name: "actionType", value: "DeleteEmail" }];

			    $.each(params, function(i,param){
			        $('<input />').attr('type', 'hidden')
			            .attr('name', param.name)
			            .attr('value', param.value)
			            .appendTo('#MyForm');
			    });

			    return true; 
			}); */

		});
		
	</script>

</head>

<body>

	<form method="post" id="MyForm" name="MyForm" action="ManageEmail">

		<table width="100%">	
		<tr>
				
			<td width="50%" style="vertical-align: top;">
			
				 <table width="100%">
				    <tr><td style=" font-size:20px; font-weight:bold;">Send Newsletter.</td></tr>
				    <tr><td>Select one template and at least one user to send newsletter.<br /></td></tr>
				    <tr>
				        <td>
				        <table border="0" cellpadding="0" cellspacing="0" width="100%">
				            <tr>
				                <td width="20%">Select Template: </td>
				                <td width="80%">
				                	<select id="ddlTemplates" name="ddlTemplates">
				                	<%
									//List all the templates in Templates folder
				                	List<String> list = FileManipulation.getFileNames(application.getRealPath("/Templates/"));
									
				                	for (int i = 0; i < list.size(); i++) 
				                	{
				                		out.print("<option value="+ list.get(i) +">"+ list.get(i) +"</option>");
				                	}
				                	%>
				                	</select>
				                </td>
				            </tr>
				        </table>
				        </td>
				    </tr>
				    <tr>
				        <td>
				        <table border="0" cellpadding="0" cellspacing="0" width="100%">
				            <tr>
				                <td width="20%">Subject : </td>
				                <td width="80%">
				                	<input type="text" id="txtSubject" name="txtSubject" style="Width:330px;">
		
				                </td>
				            </tr>
				        </table>
				        </td>
				    </tr>
				    <tr>
				        <td>
				        <table border="0" cellpadding="0" cellspacing="0" width="100%">
				            <tr>
				                <td width="20%">Display Name : </td>
				                <td width="80%"><input type="text" id="txtDisplayName" name="txtDisplayName" style="Width:330px;"></td>
				            </tr>
				        </table>
				        </td>
				    </tr>
				    <% 	
						CKEditorConfig settings = new CKEditorConfig();
						settings.addConfigValue("width","900");
						settings.addConfigValue("height","100");
					%>
				    <tr><td>Title Place Holder : </td></tr>
				    <tr><td><ckeditor:editor config="<%=settings %>" basePath="/QID/ckeditor/" editor="txtTitle" /></td></tr>
				    <tr><td>Content Place Holder : </td></tr>
				    <tr><td><ckeditor:editor  basePath="/QID/ckeditor/" editor="txtContent"  /></td></tr>
				    <tr>
				    	<td>
				            <div><input type="submit" id="btnSendNewsletter" name="btnSendNewsletter" value="Send Newsletter"/></div>
				            <div style="font-style:italic;">
				            <label id="lblNewsletterStatus">
				            	<% if (request.getAttribute("status")!= null) 
				            		out.print(request.getAttribute("status").toString());	
								%>
							</label>
				           	</div>
				        </td>
				    </tr>
				</table>
				
			
			</td>
			
			<td width="50%" style="vertical-align: top;">
			
				<!-- Tree #2 -->
				<p>
					<a href="#" id="btnSelectAll">Select all</a> -
					<a href="#" id="btnDeselectAll">Deselect all</a> -
					<a href="#" id="btnToggleSelect">Toggle select</a>
				</p>
				
				<div id="tree">
					<ul>
						
					<%
					EmailServiceImpl eis = new EmailServiceImpl();
					List<EmailDTO> emailList = eis.GetAll();
					session.setAttribute("EmailListCount", emailList.size());
					for(int i = 0; i < emailList.size(); i++)
					{
						out.print(
						"<li id='key" + emailList.get(i).getidEmail() + "'>" +
						"<input type='checkbox' id='chb-key"+ emailList.get(i).getidEmail() +
						"' name='emailAddresses' value='"+ emailList.get(i).getEmail() +"' class='' />"
						+ emailList.get(i).getEmail() + "</li>");
						
						//emailList.get(i).getEmail();
					}
					%>
	     			</ul>
				</div>				   
				 <div style="padding-top:20px;">
					<button id="btnAddEmail" name="btnAddEmail" > Add</button>
					<button id="btnDeleteEmail" name="btnDeleteEmail" > Delete</button>
				</div>
			</td>
		</tr>
		</table>
	
	   <!-- PopUp menu to add email  -->
	   <div id="overlay" class="web_dialog_overlay"></div>
	
	   <div id="dialog" class="web_dialog">
	     
			<table width="100%" border="0" cellpadding="5" cellspacing="0">
				 <tr>
				     <td style="padding: 0px 0px 0px 0px;" colspan="2">
				       <table width="100%" border="0" cellpadding="0" cellspacing="0">
				           <tr>
				               <td class="web_dialog_title">Add New Email Account</td>
				               <td class="web_dialog_title align_right" style="padding: 0 20px 0 20px;">
				                    <a id="aAddEmail" href="#">Add</a>            
				                    |
				                    <a id="btnClose" name="btnClose" class="Close" href="#">Close</a>
				                </td>
				            </tr>
				        </table>
				        </td>
				</tr>
			</table>
			
			<div>
				<center><span style=" padding-top:10%; text-align:center;" id="txtError"></span></center>
				<div style="padding-top:15%; text-align:center;">
					<input type="text" id="txtEmail"  style="width:300px;" name="txtEmail">   
				</div>
			</div>
	        
	   </div>
	</form>

</body>
</html>